package com.wjm.api.LambdaPackage;

import java.util.Arrays;
import java.util.Comparator;

/**
 * Data:2022年07月29日
 * Author:wjm
 * Content: Lambda表达式案例
 *
 *
 *  （有参数，有返回值类型 ） 用Lambda表达式写比较器comparator
 *
 */
public class LambdaDemo2 {
    public static void main(String[] args) {
        //创建People对象
        People p1 = new People("wjm",21,15000.88);
        People p2 = new People("cwt",20,14000.88);
        People p3 = new People("欧文",30,45000.99);

        //将对象存入数组
        People[] p = {p1,p2,p3};

        //使用之前匿名内部类的方式来写比较器
        Comparator<People> comparator = new Comparator<People>() {
            @Override
            public int compare(People o1, People o2) {
                return (int) (o1.getSal()-o2.getSal());
            }
        };

        //进行排序
        Arrays.sort(p,comparator);

        //遍历
        for (People people:p){
            System.out.println(people);
        }
        System.out.println("-------------------------------------------");

        //TODO 使用Lambda表达式写比较器
        Arrays.sort(p,(People o1, People o2) -> {return (int) (o1.getSal()-o2.getSal());});

        //优化的Lambda表达式（把大括号，参数类型，和return去掉）
        //Arrays.sort(p,( o1,  o2) ->  (int) (o1.getSal()-o2.getSal()));

        //遍历
        for (People people:p){
            System.out.println(people);
        }
    }

}

//创建一个类
class People{
    String name;
    int age;
    double sal;

    public People(){

    }

    public People(String name, int age, double sal) {
        this.name = name;
        this.age = age;
        this.sal = sal;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public double getSal() {
        return sal;
    }

    public void setSal(double sal) {
        this.sal = sal;
    }

    @Override
    public String toString() {
        return "People{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", sal=" + sal +
                '}';
    }
}
